package com.chenqi.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @description: 查询数据库中的用户信息
 * @program: ardai-securtiy-parent
 * @author: ChenQi
 * @create: 2021-03-2021/3/17-11-16
 */
@Slf4j
@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("要认证的用户名字:" + username);
        //1.通过请求的用户名去数据库查询用户信息
        if (!"chendake".equalsIgnoreCase(username)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //假设数据库里面的原秘密是123456
        String password = passwordEncoder.encode("123456");
        //2.查询该用户有哪一些权限

        //3.封装用户信息和权限信息
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
    }
}
